<?php

    /**
    * Nicewindow module
    * 22-05-2009 13:24
    */

    /**
    * Add operating instruction/добавление обработчика управляющей инструкции
    */
    $mikron->OperatingInstructions->AddFunction("nicewindow", "niceWindow");
    $mikron->OperatingInstructions->AddFunction("/nicewindow", "endnicewindow");

    $nicewindow = new NiceWindowClass();
    /**
    * Add Handler
    */
    $mikron->Handlers->AddPagePrintedHandler('PagePrinted', $nicewindow);

    class NiceWindowClass
    {
        /**
        * PagePrinted-handler function
        * 
        * @param mixed $PageContent Page content without template and before
        * run operating instructions
        */
        function PagePrinted(&$PageContent)
        {
            nicewindow_construct();
        }
    }

    /**
    * Templates initialization/Построение списка шаблонов
    */
    function nicewindow_construct()
    {
        if(defined('NICEWINDOW_INITIALIZED'))
        {
            return false;
        }
        define('NICEWINDOW_INITIALIZED', true);
        global $mikron;
        $styles = Array();
        $templates_dir = dirname(__FILE__)."/templates/";
        $default_style = Array("name"=>null, "directory"=>null,
            "captionforecolor"=>null, "format"=>"gif", "forecolor"=>null, "left"=>null,
            "right"=>null, "top"=>null, "bottom"=>null, "padding-top"=>"0em", "padding"=>"0em");
        $IsInitialized = true;
        $stylefile = $mikron->Cache->getCache('nicewindowstyles');
        if(!is_null($stylefile))
        {
            if(file_exists($stylefile))
            {
                return $mikron->CSS->AddFile($stylefile, 'Стили модуля NiceWindow');
            }
        }
        $files = scandir($templates_dir);
        foreach($files as $f)
        {
            $path = $templates_dir.$f;
            if(is_dir($path))
            {
                if(file_exists($path."/nicewindow.ini"))
                {
                    $settings = getSettings($path."/nicewindow.ini");
                    if(!is_null($settings))
                    {
                        $styles[] = addTemplate($path, $f, $settings, $default_style);
                    }
                }
            }
        }
        $stylebuf = '';

        foreach($styles as $item)
        {
            $style = $item['name'];
            $captionforecolor = $item['captionforecolor'];
            $forecolor = $item['forecolor'];
            $format = $item['format'];
            $dirname = WWWDirName($item['directory']."/".$style);
            $curdir = WWWDirName(__FILE__);
            $dirname = '..'.str_replace($curdir, null, $dirname);
            $LeftWidth = $item['left'];
            $RightWidth = $item['right'];
            $TopHeight = $item['top'];
            $BottomHeight = $item['bottom'];
            $PaddingTop = $item['padding-top'];
            $padding = $item['padding'];
            
            $sz = $LeftWidth;
            $szpx = $sz;

            $stylebuf .= ".corners_$style { height: 1%; overflow: hidden; }
.corners_$style h2 {color: $captionforecolor; }
.corners_$style, .corners_$style .tr, .corners_$style .bl, .corners_$style .br {padding: 0px; margin: 0px; }
.corners_$style .tr { height: 9999px; }
.corners_$style .bl { width: 9999px; }
.corners_$style { position: relative; background: url($dirname/corners.png) no-repeat -$szpx -$szpx; padding: $padding; margin: 0px; }
.corners_$style .tr, .corners_$style .bl, .corners_$style .br { position: absolute; overflow: hidden; background: url($dirname/corners.png) no-repeat; }
.corners_$style .tr { background-position: 0 -$szpx; top: 0; right: 0; bottom: $szpx; width: $szpx; }
.corners_$style .bl { background-position: -$szpx 0px; bottom: 0; left: 0; height: $szpx; right: 0; }
.corners_$style .br { background-position: 0px 0px; bottom: 0; right: 0; width: $szpx; height: $szpx; }\r\n";

            /*$stylebuf .= 
               ".nice1_$style {background: url($dirname/nice1.$format) no-repeat left top; font-size: 12pt; padding: 0px; }
                .nice2_$style {background: url($dirname/nice2.$format) repeat-x left top; font-size: 13pt; color: $captionforecolor; padding-left: .7em; vertical-align: middle; }
                .nice3_$style {background: url($dirname/nice3.$format) no-repeat right top; padding: 0px; }
                .nice4_$style {background: url($dirname/nice4.$format) repeat-y left top; padding: 0px;}
                .nice5_$style {background: url($dirname/nice5.$format) repeat left top; font-size: 10pt; padding: .7em; color: $forecolor; padding-bottom: 0px; padding-top: $PaddingTop; }
                .nice6_$style {background: url($dirname/nice6.$format) repeat-y right top; padding: 0px;}
                .nice7_$style {background: url($dirname/nice7.$format) no-repeat left bottom; font-size: 2pt; padding: 0px; }
                .nice8_$style {background: url($dirname/nice8.$format) repeat-x left bottom; font-size: 2pt; padding: 0px; }
                .nice9_$style {background: url($dirname/nice9.$format) no-repeat right bottom; font-size: 2pt; padding: 0px; }
                .nice1_$style, .nice4_$style, .nice7_$style {width: $LeftWidth; }
                .nice3_$style, .nice6_$style, .nice9_$style {width: $RightWidth; }
                .nice1_$style, .nice2_$style, .nice3_$style {height: $TopHeight; }
                .nice7_$style, .nice8_$style, .nice9_$style {height: $BottomHeight; }
                \r\n";
            */
        }
        $stylebuf = str_replace("\r\n", "\r", $stylebuf);        
        $stylebuf = str_replace("  ", " ", $stylebuf);
        $stylebuf = str_replace("  ", " ", $stylebuf);
        $stylebuf = str_replace("  ", " ", $stylebuf);
        $stylebuf = str_replace("  ", " ", $stylebuf);
        
        $stylebuf = str_replace(", ", ',', $stylebuf);
        $stylebuf = str_replace(": ", ':', $stylebuf);
        $stylebuf = str_replace(" {", '{', $stylebuf);
        $stylebuf = str_replace("; ", ';', $stylebuf);

        $mikron->Cache->setCache('nicewindowstyles', $stylebuf);
        $filename = dirname(__FILE__).'/css/'.md5($stylebuf).'.css';
        $f = fopen($filename, 'w');
        fwrite($f, $stylebuf);
        fclose($f);
        $mikron->CSS->AddFile($filename, "Стили модуля NiceWindow");
        return true;
    }

    // ф-я добавления шаблона
    function addTemplate($path, $code, $settings, & $default_style)
    {
        try
        {
            $current_style = $default_style;
            $description = $settings['nicewindow']['description'];
            $formats = $settings['nicewindow']['formats'];
            $format = "gif";
            $captionforecolor = $settings['caption']['font-color'];
            $forecolor = $settings['workspace']['font-color'];
            $paddingtop = null;
            $padding = null;
            if(isset($settings['workspace']['padding-top'])) {$paddingtop = $settings['workspace']['padding-top']; }
            if(isset($settings['workspace']['padding'])) {$padding = $settings['workspace']['padding']; }
            $left = $settings['border']['left'];
            $right = $settings['border']['right'];
            $top = $settings['border']['top'];
            $bottom = $settings['border']['bottom'];
            $current_style['name'] = $code;
            $current_style['directory'] = $path;
            $current_style['captionforecolor'] = $captionforecolor;
            $current_style['format'] = $format;
            $current_style['forecolor'] = $forecolor;
            $current_style['left'] = $left;
            $current_style['right'] = $right;
            $current_style['top'] = $top;
            $current_style['bottom'] = $bottom;
            if(!is_null($paddingtop))
            {
                $current_style['padding-top'] = $paddingtop;
            }
            if(!is_null($padding))
            {
                $current_style['padding'] = $padding;
            }
            return $current_style;
        }
        catch(Exception $ex)
        {
            CriticalError("Не удалось загрузить стили для модуля nicewindow. ".$ex->getMessage(), null, true);
        }
    }

    function getSettings($path)
    {
        $ini_array = parse_ini_file($path, true);
        if(!array_key_exists("nicewindow", $ini_array))
        {
            return null;
        }
        if(!array_key_exists("border", $ini_array))
        {
            return null;
        }
        if(!array_key_exists("caption", $ini_array))
        {
            return null;
        }
        if(!array_key_exists("workspace", $ini_array))
        {
            return null;
        }
        return $ini_array;
    }

    $nicewindowstack = Array();
    $nicewindowstyleisinit = false;

    function niceWindow($parameters)
    {
        global $mikron;
        $class = $mikron->Tools->GetParam($parameters, 'class', null);
        $width = $mikron->Tools->GetParam($parameters, 'width', null);
        $height = $mikron->Tools->GetParam($parameters, 'height', null);
        $caption = $mikron->Tools->GetParam($parameters, 'caption', null);
        $style = $parameters['style'];
        if(substr($style, 0, 1) != '_')
        {
            $style = '_'.$style;
        }
        startnicewindow($caption, $style, $width, $height, $class);
    }

    function startnicewindow($caption, $style = "_blue", $width = null, $height = null, $class = null)
    {
        /*
        {{$BODY}}</td></tr><tr><td valign="bottom">{{INFOMAT_MAIN_BUTTONS}}
        */
        global $nicewindowstack;
        $nicewindowstack[] = $style;
        $stylebuf = null;
        
        if(is_null($class))
        {
            $class = 'corners'.$style;
        }
        else
        {
            $class .= ' corners'.$style;
        }
        $classAttr = sprintf('class="%s"', $class);
        ?><table <?php echo $classAttr; ?> border="0" cellspacing="0" cellpadding="0" width="100%">
        <tr><td><?php
        if(!is_null($caption))
        {
            echo sprintf('<h2>%s</h2>', $caption);
        }
    }

    function endnicewindow()
    {
        global $nicewindowstack;
        $style = array_pop($nicewindowstack);
        echo ' <b class="tr"></b><b class="bl"></b><b class="br"></b>';
        ?></td></tr></table><?php
    }

?>